﻿using SharpSoft.WPF;
using System;
using System.Collections.Generic;
using System.Text;

namespace System.Windows.Controls
{
    public static class UIElementExtensions
    {
        #region 用户操作闲置时触发
        /// <summary>
        /// 用户操作闲置时触发指定的功能
        /// </summary>
        /// <param name="element"></param>
        /// <param name="time">等待限制时长</param>
        /// <param name="action">触发的委托</param>
        public static void UserIdleRun(this UIElement element, TimeSpan time, Action action)
        {
            if (idleTimer != null)
            {
                throw new Exception("目前仅支持使用一次。");
            }
            idleAction = action;
            waitTime = time;
            element.PreviewMouseDown += Element_PreviewMouseDown;
            element.PreviewTouchDown += Element_PreviewTouchDown;
            idleTimer = new Threading.DispatcherTimer();
            idleTimer.Interval = TimeSpan.FromSeconds(1);
            idleTimer.Tick += IdleTimer_Tick;
            IdleTime = DateTime.Now;
            idleTimer.Start();
        }

        private static void Element_PreviewTouchDown(object sender, Input.TouchEventArgs e)
        {
            IdleTime = DateTime.Now;
        }

        private static void IdleTimer_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now - IdleTime > waitTime)
            {
                IdleTime = DateTime.Now;
                idleAction?.Invoke();
            }
        }
        private static Action idleAction;
        private static TimeSpan waitTime;
        private static DateTime IdleTime;
        private static System.Windows.Threading.DispatcherTimer idleTimer;
        private static void Element_PreviewMouseDown(object sender, Input.MouseButtonEventArgs e)
        {
            IdleTime = DateTime.Now;
        }
        #endregion

        /// <summary>
        /// 获取控件所属的窗体
        /// </summary>
        /// <param name="ui"></param>
        /// <returns></returns>
        public static Window GetWindow(this UIElement ui)
        {
            if (ui is Window win)
            {
                return win;
            }

            return VisualHelper.FindParent<Window>(ui);
        }
    }
}
